package cn.iocoder.yudao.module.service.service.leavemessage;

import cn.iocoder.yudao.framework.tenant.core.util.TenantUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

import cn.iocoder.yudao.module.service.controller.admin.leavemessage.vo.*;
import cn.iocoder.yudao.module.service.dal.dataobject.leavemessage.ServiceLeaveMessageDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.service.dal.mysql.leavemessage.ServiceLeaveMessageMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.service.enums.ErrorCodeConstants.*;

/**
 * 客户留言 Service 实现类
 *
 * @author 数创万维
 */
@Service
@Validated
public class ServiceLeaveMessageServiceImpl implements ServiceLeaveMessageService {

    @Resource
    private ServiceLeaveMessageMapper leaveMessageMapper;

    @Override
    public Long createLeaveMessage(ServiceLeaveMessageSaveReqVO createReqVO) {
        // 插入
        ServiceLeaveMessageDO leaveMessage = BeanUtils.toBean(createReqVO, ServiceLeaveMessageDO.class);

        // 使用租户工具类写入
        TenantUtils.execute(createReqVO.getTenantId(), () -> {
            leaveMessageMapper.insert(leaveMessage);
        });

        // 返回
        return leaveMessage.getId();
    }

    @Override
    public void updateLeaveMessage(ServiceLeaveMessageUpdateReqVO updateReqVO) {
        // 校验存在
        validateLeaveMessageExists(updateReqVO.getId());
        // 更新
        ServiceLeaveMessageDO updateObj = BeanUtils.toBean(updateReqVO, ServiceLeaveMessageDO.class);
        leaveMessageMapper.updateById(updateObj);
    }

    @Override
    public void deleteLeaveMessage(Long id) {
        // 校验存在
        validateLeaveMessageExists(id);
        // 删除
        leaveMessageMapper.deleteById(id);
    }

    private void validateLeaveMessageExists(Long id) {
        if (leaveMessageMapper.selectById(id) == null) {
            throw exception(LEAVE_MESSAGE_NOT_EXISTS);
        }
    }

    @Override
    public ServiceLeaveMessageDO getLeaveMessage(Long id) {
        return leaveMessageMapper.selectById(id);
    }

    @Override
    public PageResult<ServiceLeaveMessageDO> getLeaveMessagePage(ServiceLeaveMessagePageReqVO pageReqVO) {
        return leaveMessageMapper.selectPage(pageReqVO);
    }

}